package com.alien.admin.modules.quartz.task;

import com.alien.admin.modules.deploy.service.DeployRecService;
import com.alien.admin.modules.utils.MyDateUtils;
import com.alien.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright (C), 2014-2021, 厦门神州鹰软件科技有限公司
 * FileName: ClearTableTask
 *
 * @author: zengzf
 * Date:     2021/12/20 16:49
 * Description:
 * History:
 */
@Slf4j
@Component
public class ClearTableTask {

    @Autowired
    private DeployRecService deployRecService;

    @Value("${clearTableConfig:debug->15,test->15,rc->30,huawei_test->31}")
    String clearTableConfig;

    /**
     * 清理部署记录表的数据
     *
     */
    public void clearTableOfDpDeployRec() {
        log.info("start clearTable -> DpDeployRec");
        Map<String, Integer> configMap = parseClearTableConfig();
        for (Map.Entry<String, Integer> e : configMap.entrySet()) {
            processOneEnvTable(e.getKey(), e.getValue());
        }
        log.info("finish clearTable -> DpDeployRec");
    }

    /**
     * 解析配置的字符串，返回一个Map， key是env， value是nDay的值
     *
     * @return
     */
    public Map<String, Integer> parseClearTableConfig() {
        System.out.println("clearTableConfig : " + clearTableConfig);
        String[] arrConfig = clearTableConfig.trim().split(",");
        Map<String, Integer> result = new HashMap<>();
        for (String s : arrConfig) {
            String[] items = s.trim().split("->");
            result.put(items[0].trim(), Integer.valueOf(items[1].trim()));
        }
        return result;
    }

    /**
     * 清理某个环境下的记录。
     *
     * @param env
     * @param nDay
     */
    public void processOneEnvTable(String env, Integer nDay) {
        if (StringUtils.isBlank(env)) {
            log.error("env is null!");
            return;
        }
        if (nDay == null) {
            log.error("nDay is null!");
            return;
        }
        Date nDayAgo = MyDateUtils.getNDayAgo(nDay);
        Timestamp timestamp = new Timestamp(nDayAgo.getTime());
        deployRecService.deleteByEnvAndDeployTime(env, timestamp);
    }

}

